<script setup>
import { ref, reactive, useTemplateRef, onMounted } from 'vue';
import { getWordTemSave, getWordTemEdit } from '@/api/index.js';

const ruleFormRef = useTemplateRef('ruleFormRef');
if (ruleFormRef.value) {
  ruleFormRef.value.resetFields();
  ruleFormRef.value.clearValidate();
}
const ruleForm = reactive({
  name: '',
  url: '', //本地文件路径
});
const rules = reactive({
  name: [{ required: true, message: '请输入笔录模板名称', trigger: 'blur' }],
});

//记录编辑状态的
const editId = ref('');

const openFile = (openType = '*.docx;*.doc') => {
  //   let dialog = window.Application.FileDialog(1);

  //   if (dialog.Show() === -1) {
  //     console.log('选择的了文件');
  //     dialog.Execute()
  //   }
  let openTypeStr = `*.${openType}`;
  let diyFilters = [
    {
      Extensions: '*.docx;*.txt',
      Description: 'doc文档',
    },
    {
      Extensions: '*.docx;*.doc',
      Description: 'doc文档和docx文档',
    },
    {
      Extensions: '*.*',
      Description: '所有文档',
    },
  ];
  let dialog = window.Application.FileDialog(1);
  //遍历打印所有Filters;
  //   for (let i = 1; i <= dialog.Filters.Count; i++) {
  // console.log('--', dialog.Filters.Item(i).Extensions, '2222', dialog.Filters.Item(i).Description);
  //   }
  //   diyFilters.map((item) => {
  //     dialog.Filters.Add(item.Description, item.Extensions, 1); //参数1：类型的描述；参数2：类型的后缀名，需要带上*.，多个用；分隔 ；参数3：插入的位置
  //   });
  dialog.Filters.Add('doc文档和docx文档', '*.docx;*.doc', 1);
  //   let defaultIndex = 1;
  //   for (let i = 1; i <= dialog.Filters.Count; i++) {
  //     let Extensions = dialog.Filters.Item(i).Extensions.split(';');
  //     if (Extensions.includes(openTypeStr)) {
  //       if (Extensions.length == 1) {
  //         defaultIndex = i;
  //         break;
  //       } else if (defaultIndex == 0) {
  //         defaultIndex = i;
  //       }
  //     }
  //   }
  //   dialog.InitialFileName = 'C:\Users\Mr.Lu\Desktop'; //初始显示的路径或文件名
  dialog.FilterIndex = 1; //默认打开的格式的Index
  dialog.AllowMultiSelect = false; //单选，true为多选
  // dialog.InitialView=7;//目前暂不支持设置
  if (dialog.Show() === -1) {
    dialog.Execute();
  }
};

const openFileAndExt = () => {
  let dialog = window.Application.FileDialog(1);
  dialog.FilterIndex = 7; //默认打开的格式的Index
  dialog.AllowMultiSelect = false; //单选，true为多选
  dialog.Filter = '*.docx,*.doc';
  if (dialog.Show() === -1) {
    dialog.Execute();
  }
};

//提交
const submitForm = () => {
  if (!ruleFormRef.value) {
    return;
  }
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      // 模版内容为空
      if (window.Application.ActiveDocument.Content.Text.trim() === '' || window.Application.ActiveDocument.Content.Text.trim() === '\r') {
        window.alert('模版内容为空，请输入内容！');
        return false;
      }
      window.Application.ActiveDocument.Save();
      //   console.log('submit!');
      ruleForm.url = window.Application.ActiveDocument.FullName;
      const legaExts = ['.doc', '.docx'];
      let name = ruleForm.url.toLowerCase(); //文件名转小写
      if (!legaExts.some((ig) => name.endsWith(ig))) {
        ElMessage({
          message: `附件不存在或者未保存！`,
          type: 'warning',
          plain: true,
        });
        return false;
      }
      //新增
      if (!editId.value) {
        getWordTemSave({
          name: ruleForm.name,
          url: ruleForm.url,
        }).then((res) => {
          window.alert(res || '保存成功');
          Object.assign(ruleForm, {
            name: '',
            url: '', //本地文件路径
          });
        });
      } else {
        //编辑
        getWordTemEdit({
          name: ruleForm.name,
          id: editId.value,
        }).then((res) => {
          window.alert(res || '编辑成功');
        });
      }

      //   console.log(ruleForm);
    } else {
      console.log('error submit!');
    }
  });
};
const submitFormAndExt = () => {
  if (!ruleFormRef.value) {
    return;
  }
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      // 模版内容为空
      if (window.Application.ActiveDocument.Content.Text.trim() === '' || window.Application.ActiveDocument.Content.Text.trim() === '\r') {
        window.alert('模版内容为空，请输入内容！');
        return false;
      }
      window.Application.ActiveDocument.Save();
      //   console.log('submit!');
      ruleForm.url = window.Application.ActiveDocument.FullName;
      const legaExts = ['.doc', '.docx'];
      let name = ruleForm.url.toLowerCase(); //文件名转小写
      if (!legaExts.some((ig) => name.endsWith(ig))) {
        ElMessage({
          message: `附件不存在或者未保存！`,
          type: 'warning',
          plain: true,
        });
        return false;
      }

      //新增
      if (!editId.value) {
        getWordTemSave({
          name: ruleForm.name,
          url: ruleForm.url,
        }).then((res) => {
          let tsId = window.Application.PluginStorage.getItem('moBanGuanLi');
          if (tsId) {
            let tskpane = window.Application.GetTaskPane(tsId);
            tskpane.Visible = false;
          }
          window.alert(res || '保存成功');
          Object.assign(ruleForm, {
            name: '',
            url: '', //本地文件路径
          });
        });
      } else {
        //编辑
        getWordTemEdit({
          name: ruleForm.name,
          id: editId.value,
        }).then((res) => {
          let tsId = window.Application.PluginStorage.getItem('moBanGuanLi');
          if (tsId) {
            let tskpane = window.Application.GetTaskPane(tsId);
            tskpane.Visible = false;
          }
          window.alert(res || '编辑成功');
          Object.assign(ruleForm, {
            name: '',
            url: '', //本地文件路径
          });
        });
      }
    } else {
      console.log('error submit!');
    }
  });
};
onMounted(() => {
  let fileName = window.Application.ActiveDocument.Name;
  let emptyText = window.Application.ActiveDocument.Content.Text.trim() === '' || window.Application.ActiveDocument.Content.Text.trim() === '\r';
  //名字是否包含 新增模版 字符
  let flagAdd = true; //默认新增
  let editoradd = window.Application.PluginStorage.getItem('editoradd');
  if (editoradd) {
    editId.value = '';
    let arr = editoradd.split('/');
    if (arr && arr.length === 2) {
      flagAdd = arr[0] === 'add' ? true : false;
      if (!flagAdd) {
        editId.value = arr[1]; //记录编辑的id
      }
    }
  }
  //设置文件名称
  if (fileName && !emptyText) {
    let arr = fileName.split('.');
    if (flagAdd) {
      ruleForm.name = '';
    } else {
      ruleForm.name = arr[0];
    }
  }
});
</script>

<template>
  <div class="mobanguanli flex flex-col">
    <div class="top flex-1">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto">
        <el-form-item label="笔录模板名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入笔录模板名称" maxlength="20" clearable />
        </el-form-item>
        <el-form-item label="word文档导入">
          <el-button type="primary" @click="openFileAndExt"> 导入模版 </el-button>
        </el-form-item>
      </el-form>
      <el-divider></el-divider>
    </div>
    <div class="bottom flex justify-center">
      <el-button type="primary" @click="submitForm" class="m-r-[20px]">保存</el-button>
      <el-button type="primary" @click="submitFormAndExt" class="m-l-[20px]">保存并退出</el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.mobanguanli {
  height: 100%;
}
</style>
